import {
  AfterViewInit,
  ChangeDetectionStrategy,
  Component,
  ElementRef, EventEmitter,
  OnDestroy,
  OnInit, Output
} from '@angular/core';
import  {jsPanel}  from 'jspanel4/es6module/jspanel.min.js'
import {BehaviorSubject, Subject} from "rxjs";
import {skip, takeUntil} from "rxjs/operators";

@Component({
  selector: 'app-jspanelx',
  template: `
    <ng-content></ng-content>
  `,
  styles: [
  ],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class JspanelxComponent implements OnInit, AfterViewInit, OnDestroy {

  panel = null
  isOpen$ = new BehaviorSubject(false)
  destroy$ = new Subject()
  constructor(
    private el: ElementRef,
  ) { }

  ngOnInit(): void {
  }

  open() {
    const nativeEl = this.el.nativeElement as HTMLElement
      this.panel = jsPanel.create({
        content: nativeEl,
        animateIn: 'jsPanelFadeIn',
        contentSize: '600 auto',
        theme: '#3893ee',
        onclosed: (panel) => {
          this.panel = null
        }
    })
  }

  close() {
    if(!this.panel) { return }
    this.panel.close()
  }

  ngAfterViewInit() {
    const el = this.el.nativeElement as HTMLElement
    const parentEl = el.parentNode
    parentEl.removeChild(el)

    this.isOpen$.pipe(
       skip(1),
      takeUntil(this.destroy$)
    ).subscribe(value => {
      if (this.panel) {
        this.close()
      } else {
        this.open()
      }
    })
  }

  ngOnDestroy() {
    this.destroy$.next()
    this.destroy$.complete()
    this.close()
  }

}
